# == Schema Information
#
# Table name: sales_firms
#
#  id          :integer          not null, primary key
#  customer_id :integer
#  name        :string(255)
#  province_id :integer
#  city_id     :integer
#  short_name  :string(255)
#  address     :string(255)
#  website     :string(255)
#  phone       :string(255)
#  fax         :string(255)
#  email       :string(255)
#  rating      :integer
#  parent_id   :integer
#  notes       :string(4000)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class Sales::Firm < ApplicationRecord
  extend Enumerize
  belongs_to :province, :class_name => 'Base::Province', foreign_key: 'province_id'
  belongs_to :city, :class_name => 'Base::City', foreign_key: 'city_id'

  has_many :contacts, :class_name => 'Sales::Contact', foreign_key: 'firm_id'
  has_many :follow_ups, :class_name => 'Sales::FollowUp', foreign_key: 'firm_id'
  has_many :leads, :class_name => 'Sales::FirmLead', foreign_key: 'firm_id'
  has_many :finance_infos, :class_name => 'Sales::FinanceInfo', foreign_key: 'firm_id'

  has_one :firm_detail, :class_name => 'Sales::FirmDetail', foreign_key: 'firm_id'

  scope :this, -> {where(customer_id: Customer.current&.id)}

  RATING = {nice: 1, normal: 2, bad: 3}
  enumerize :rating, in: RATING,  predicates: {prefix: true}, scope: true


  validates_presence_of :name, :message=> '必须填写公司名'


  accepts_nested_attributes_for :contacts, allow_destroy: true, reject_if: :all_blank
  accepts_nested_attributes_for :firm_detail, reject_if: :all_blank

  # 所有leads在firm里面作为类方法定义获取，没有创建指定leads的时候就new一个
  Sales::FirmLead::LEADS_TYPE.each do |leads_name, leads_id|
    define_method "#{leads_name}_lead" do
      @all_leads = self.leads
      @all_leads.find{|l|l.leads_type==leads_id} ||
          Sales::FirmLead.new(leads_type: leads_id, firm_id: self.id, user_id: nil, stage: 1, begin_at: Time.now)
    end
  end

  def to_s
    name
  end

  def province_city
    [self.province,self.city].compact.join('/')
  end

  def editable_attributes_json
    self.to_json(only: Sales::Firm.column_names-['created_at','updated_at','id'])
  end
end
